<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('houses.quick Search Fields') })">
            <div class="mlr-12" style="margin-left: 12px">
                <el-button type="primary" @click="handleImport">{{ '导入' }}</el-button>
                <el-button type="primary"  :disabled="baTable.table.selection!.length > 0 ? false : true" @click="batchedPass">{{ '批量通过' }}</el-button>
                <el-button type="info" @click="customFieldsHandle">{{ '自定义字段是否必填' }}</el-button>
            </div>
        </TableHeader>
        <el-row :gutter="20">
            <el-col :span="2">
                <h5 class="mb-2" style="font-size: 16px; text-align: center; background: #fff; border-bottom: 1px solid #4d9efc; padding: 10px">
                    房源类型
                </h5>
                <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
                    <el-menu-item index="0" @click="tabFromType" style="justify-content: center"> 自有房源 </el-menu-item>
                    <el-menu-item index="1" @click="tabFromType" style="justify-content: center"> 客户房源 </el-menu-item>
                </el-menu>
            </el-col>
            <el-col :span="22">
                <!-- 表格 -->
                <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
                <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
                <Table ref="tableRef">
                    <!-- 请注意 #test 它是自定义的插槽名称 -->
                    <template #test>
                        <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                        <el-table-column prop="status" label="状态" width="180">
                            <template #default="scope">
                                <div style="display: flex; align-items: center">
                                    <span
                                        style="display: inline-block; width: 10px; height: 10px; border-radius: 50%"
                                        :class="'status-' + scope.row.status"
                                    ></span>
                                    <span style="margin-left: 10px">{{ scope.row.status_text }}</span>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                </Table>
            </el-col>
        </el-row>
        <!-- 表单 -->
        <PopupForm />
        <ImportForm />
        <Info />
        <Check />
        <customFileds v-if="['customFields'].includes(baTable.form.operate!)" />
    </div>
</template>

<script setup lang="ts">
import ImportForm from './ImportForm.vue'
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Info from './info.vue'
import customFileds from './customFileds.vue'

import Check from './check.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { checkSumit } from '/@/api/backend/hourse'
import { ElMessageBox, ElNotification } from 'element-plus'

defineOptions({
    name: 'houses',
})
const dialogVisible = ref(false)

const handleClose = (done: () => void) => {}
const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
import { useRoute } from 'vue-router'

const route = useRoute()
const handleImport = () => {
    baTable.form.operate! = 'import'
    baTable.form.loading = false
    baTable.table.extend!.showPreImport = true
    baTable.form.extend!.fileUploadStatus = 'wait'
}
const customFieldsHandle = () => {
    baTable.form.operate! = 'customFields'
}
/**
 * 示例核心代码(2/3)
 * 表格操作按钮组 optButtons 只是个普通的数组，此处向其 push 一个 OptButton
 */
optButtons.push(
    {
        render: 'tipButton',
        name: 'info', // name 是任意的
        title: '', // title 是语言翻译 key
        text: '详情',
        type: '',
        icon: '',
        click(row, field) {
            // 在 extend 上自定义一个变量标记详情弹窗显示状态，详情组件内以此判断显示即可！
            baTable.table.extend!.showInfo = true
            // 您也可以使用 baTable.form.operate，默认情况它有三个值`Add、Edit、空字符串`，前两个值将显示添加和编辑弹窗
            // 您也可以再来个 loading 态，然后请求详情数据等
            baTable.table.extend!.infoLoading = true
            baTable.table.extend!.infoData = row
            setTimeout(() => {
                baTable.table.extend!.infoLoading = false
            }, 200)
        },
    },
    {
        render: 'tipButton',
        name: 'info', // name 是任意的
        title: '', // title 是语言翻译 key
        text: '驳回',
        type: '',
        icon: '',
        // 按钮是否显示，请返回布尔值
        display: (row: TableRow, field: TableColumn) => {
            return row.status == 2 ? true : false
        },
        click(row, field) {
            // 在 extend 上自定义一个变量标记详情弹窗显示状态，详情组件内以此判断显示即可！
            //baTable.table.extend!.showInfo =true
            baTable.form.operate! = 'check'
            // 您也可以使用 baTable.form.operate，默认情况它有三个值`Add、Edit、空字符串`，前两个值将显示添加和编辑弹窗
            // 您也可以再来个 loading 态，然后请求详情数据等
            baTable.table.extend!.infoLoading = true
            checkForm.status=3;
            setTimeout(() => {
                baTable.table.extend!.infoData = row
                baTable.table.extend!.infoLoading = false
            }, 200)
        },
    },
    {
        render: 'tipButton',
        name: 'info', // name 是任意的
        title: '', // title 是语言翻译 key
        text: '通过',
        type: '',
        icon: '',
        // 按钮是否显示，请返回布尔值
        display: (row: TableRow, field: TableColumn) => {
            return row.status == 2 ? true : false
        },
        click(row, field) {
            ElMessageBox.confirm('确定要通过?')
                .then(() => {
                    checkForm.id = row.id
                    checkForm.status = 1
                    confirmClick(row)
                })
                .catch(() => {
                    // catch error
                })
        },
    },
    {
        render: 'tipButton',
        name: 'info', // name 是任意的
        title: '', // title 是语言翻译 key
        text: '下架',
        type: '',
        icon: '',
        // 按钮是否显示，请返回布尔值
        display: (row: TableRow, field: TableColumn) => {
            return row.status == 1 ? true : false
        },
        click(row, field) {
            ElMessageBox.confirm('确定要下架?')
                .then(() => {
                    checkForm.id = row.id
                    checkForm.status = 0
                    confirmClick(row)
                })
                .catch(() => {
                    // catch error
                })
        },
    },
    {
        render: 'tipButton',
        name: 'info', // name 是任意的
        title: '', // title 是语言翻译 key
        text: '上架',
        type: '',
        icon: '',
        // 按钮是否显示，请返回布尔值
        display: (row: TableRow, field: TableColumn) => {
            return row.status == 0 ? true : false
        },
        click(row, field) {
            ElMessageBox.confirm('确定要上架?')
                .then(() => {
                    checkForm.id = row.id
                    checkForm.status = 1
                    confirmClick(row)
                })
                .catch(() => {
                    // catch error
                })
        },
    }
)
const checkForm = reactive({
    check_mark: '',
    id: '',
    status: '',
})
function confirmClick(row: TableRow) {
    checkSumit(checkForm)
        .then((result) => {
            checkForm.check_mark = ''
            checkForm.id = ''
            baTable.form.operate! = ''
            baTable.getIndex()
            ElNotification({
                title: '',
                message: result.msg,
                type: 'success',
            })
        })
        .catch((err) => {})
}
/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/Houses/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            //{ label: t('houses.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { label: t('houses.name'), prop: 'name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            {
                label: t('houses.category_ids'),
                prop: 'category_text',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator:false,
                sortable: false,
            },
            {
                label: t('houses.category_ids'),
                prop: 'category_ids',
                show: false,
                operator: 'LIKE',
                comSearchRender: 'remoteSelect',
                remote: {
                    // 主键，下拉 value
                    pk: 'id',
                    // 字段，下拉 label
                    field: 'name',
                    remoteUrl: '/admin/category/index',
                    // 额外的请求参数
                    params: { catetype: 'archives_tags' },
                },
            },
            // { label: t('houses.category_ids'), prop: 'category_ids', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            // { label: t('houses.tags_ids'), prop: 'tags_ids', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('houses.city'), prop: 'city_text', align: 'center', operator: false },
            //{ label: t('houses.address'), prop: 'address', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('houses.acreage'), prop: 'acreage', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('houses.rent_money'), prop: 'rent_money', align: 'center', operator: 'RANGE', sortable: false },
            // { label: t('houses.user_ids'), prop: 'user_ids', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },

            {
                label: t('houses.user_ids'),
                prop: 'user.nickname',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                render: 'tags',
                operator: 'LIKE',
            },
            {
                label: t('手机号'),
                prop: 'user.mobile',
                align: 'center',
                width: 120,
                operatorPlaceholder: t('Fuzzy query'),
                render: 'tags',
                operator: 'LIKE',
            },
            {
                label: t('houses.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd',
            },
            // { label: t('houses.has_bounty'), prop: 'has_bounty', align: 'center', operator: 'RANGE', sortable: false, replaceValue: { '0': t('houses.has_bounty 0'), '1': t('houses.has_bounty 1') } },
            { label: t('houses.reward'), prop: 'reward', align: 'center', operator: 'RANGE', sortable: 'custom' },
            { label: t('houses.weigh'), prop: 'weigh', align: 'center', operator: false, sortable: 'custom' },
            // { label: t('houses.image'), prop: 'image', align: 'center', render: 'image', operator: false },
            //  { label: t('houses.images'), prop: 'images', align: 'center', render: 'images', operator: false },
            // { label: t('houses.status'), prop: 'status', align: 'center', operator: 'RANGE', sortable: false, replaceValue: { 0: t('houses.status 0'), 1: t('houses.status 1') } },
            { label: t('houses.status'), render: 'slot', slotName: 'test', operator: false , sortable: 'custom'},

            { label: t('houses.status'), prop: 'status', align: 'center', render: 'switch',show:false , operator: 'eq', sortable: false, replaceValue: { '0': t('已下架'), '1': t('已上架'),'2': t('待审核'),'3': t('已驳回'),'4': t('佣金已支付')}, sortable: 'custom' },
            //0 => '已下架', 1 => '已上架', 2 => '待审核', 3 => '已驳回'
           
            // {
            //     label: t('houses.status'),
            //     prop: 'status',
            //     align: 'center',
            //     render: 'tag',
            //     custom: { 0: t('houses.status 0'), 1: t('houses.status 1') },
            //     replaceValue: { 0: t('houses.status 0'), 1: t('houses.status 1') }
            // },
            //  { label: t('houses.rent_free'), prop: 'rent_free', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            //  { label: t('houses.start_rent'), prop: 'start_rent', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('houses.paymethod'), prop: 'paymethod', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '1': t('houses.paymethod 1'), '3': t('houses.paymethod 3'), '10': t('houses.paymethod 10'), '6': t('houses.paymethod 6'), '12': t('houses.paymethod 12') } },
            // { label: t('houses.longitude'), prop: 'longitude', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('houses.latitude'), prop: 'latitude', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('houses.industry'), prop: 'industry', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('houses.surround'), prop: 'surround', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('houses.property'), prop: 'property', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('Operate'), align: 'center', width: 140, render: 'buttons', buttons: optButtons, operator: false },

            // 加了按钮，您可以将 width 设置得更大一点
            { label: t('Operate'), align: 'center', width: 240, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
        defaultOrder: { prop: 'reward', order: 'desc' },
    },
    {
        defaultItems: {
            address: null,
            acreage: 0,
            rent_money: 0,
            has_bounty: 1,
            reward: 0,
            weigh: 0,
            status: 1,
            rent_free: null,
            start_rent: null,
            paymethod: '1',
            industry: null,
            surround: null,
            property: null,
            longitude:102.71,
            latitude:25.04,
            name:'房源信息'
        },
    }
)

const api = baTable.api as baTableApi
const batchedPass=()=>{
    const operate = 'batchPass'
    api.postData(operate, { ids: baTable.getSelectionIds()})
        .then((res) => {baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
        baTable.table.showComSearch = true
    })
        })
        .finally((err) => {})
}


provide('baTable', baTable)
const tabFromType = (e) => {
    baTable.table.filter!.search = [{ field: 'from_type', val: e.index, operator: '=' }]
    baTable.getIndex()
}
onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
     // 初始化公共搜索数据
    baTable.initComSearch(route?.query ? route.query : {})
    
    
    baTable.table.filter.order= baTable.table.defaultOrder.prop+','+baTable.table.defaultOrder.order
   
    
    if( route.query){
        let search =[];
        for (var index in route.query) {
            const element = route.query[index];
            console.log(element,'>>>>');
            search.push({ field: index, val: element, operator: '=' })
        }
        baTable.table.filter!.search =search
    }
    baTable.getIndex()?.then(() => {
        baTable.dragSort()
        baTable.table.showComSearch = true
    })
})
</script>

<style scoped lang="scss">
.status-0 {
    background-color: #a4a4a4; //已下架
}
.status-1 {
    background-color: #54d39e; //已经上架
}
.status-2 {
    background-color: #f99b59; //待审核
}
.status-3 {
    background-color: #ec4d4f; //已驳回
}
</style>
